<?php

namespace app\admin\controller\shopro\wallet;

use app\admin\controller\shopro\Common;
use app\admin\model\Admin;
use app\admin\model\shopro\user\WalletLog as WalletLogModel;
use addons\shopro\library\Operator;
use app\admin\model\User;

class PaymentGoods extends Common
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new WalletLogModel;
    }
    //新增----货款记录
    /**
     * 货款记录
     */
    public function index($id="")
    {
        if (false === $this->request->isPost()) {
            $exportConfig = (new \addons\shopro\library\Export())->getConfig();
            $this->assignconfig("save_type", $exportConfig['save_type'] ?? 'download');
            return $this->view->fetch();
        }
        $list_rows = $this->request->param('list_rows', 10);
        $walletLogs = WalletLogModel::with("user")->sheepFilter()->payment_goods()
            ->order("createtime desc,id desc")->paginate($list_rows);
        // 多态关联 oper
        $morphs = [
            'user' => \app\admin\model\shopro\user\User::class,
            'admin' => \app\admin\model\Admin::class,
            'system' => \app\admin\model\Admin::class,
        ];
        $walletLogs = morph_to($walletLogs, $morphs, ['oper_type', 'oper_id']);
        $walletLogs = $walletLogs->toArray();

        // 解析操作人信息
        foreach ($walletLogs['data'] as &$log) {
            $log['oper'] = Operator::info($log['oper_type'], $log['oper'] ?? null);
        }
        $this->success('', null, $walletLogs);
    }

    public function export()
    {
        $cellTitles = [
            // 订单表字段
            'id' => 'ID',
            'user.id' => '用户ID',
            'user.nickname' => '用户昵称',
            'amount' => '变动余额',
            'before' => '变更前',
            'after' => '剩余余额',
            'oper.id' => '操作人ID',
            'oper.nickname' => '操作人昵称',
            'createtime' => '交易时间',
            'memo' => '备注',
        ];

        // 数据总条数
        $total = $this->model->sheepFilter()->payment_goods()->count();
        if ($total <= 0) {
            $this->error('导出数据为空');
        }

        $export = new \addons\shopro\library\Export();
        $params = [
            'file_name' => '货款明细列表',
            'cell_titles' => $cellTitles,
            'total' => $total,
            'is_sub_cell' => true,
            'sub_start_cell' => 'activity_type_text',
            'sub_field' => 'items'
        ];

        $result = $export->export($params, function ($pages) use (&$total_order_amount, &$total_pay_fee, &$total_real_pay_fee, &$total_discount_fee, &$total_score_amount, $total) {
            $datas = $this->model->sheepFilter()->payment_goods()->with(['user'])
                ->limit((($pages['page'] - 1) * $pages['list_rows']), $pages['list_rows'])
                ->select();
            $datas = collection($datas);
            $newDatas = [];
            $goods_list="";
            $items = [];
            foreach ($datas as &$item) {
                $nickname="系统";
                if($item["oper_type"]=="user"){
                    //用户
                    $nickname=User::where(["id"=>$item["oper_id"]])->column("nickname")[0];
                }
                if($item["oper_type"]=="admin"){
                    //平台
                    $nickname=Admin::where(["id"=>$item["oper_id"]])->column("nickname")[0];
                }
                $data = [
                    // 订单表字段
                    'id' => $item['id'],
                    'user.nickname' =>$item["user"]["nickname"]??'',
                    'user.id' =>$item["user"]["id"]??0,
                    'amount' =>$item["amount"],
                    'before' =>$item["before"],
                    'after' =>$item["after"],
                    'createtime' =>$item["createtime"],
                    'oper.id' =>$item["oper_id"],
                    'oper.nickname' =>$nickname,
                    'memo' =>$item["memo"],
                ];

                $data['items'] = $items;
                $data['goods_list'] = $goods_list;
                $newDatas[] = $data;
            }
            return $newDatas;
        });

        $this->success('导出成功' . (isset($result['file_path']) && $result['file_path'] ? '，请在服务器: “' . $result['file_path'] . '” 查看' : ''), null, $result);
    }

}
